<template>
  <Layout>
    <div class="security-page">
      <!-- 页面标题 -->
      <div class="page-header">
        <h2>安全设置</h2>
        <p>保护您的账户安全，设置多重安全防护</p>
      </div>

      <!-- 安全概览 -->
      <SecurityOverview 
        :security-score="securityScore"
        :calculate-security-score="calculateSecurityScore"
        :get-progress-color="getProgressColor"
        :format-score="formatScore"
      />

      <!-- 安全设置项 -->
      <SecuritySettingsPanel 
        :security-settings="securitySettings"
        @change-password="showPasswordDialog = true"
        @bind-email="showEmailBindDialog = true"
        @unbind-email="handleUnbindEmail"
        @toggle-login-protection="handleToggleLoginProtection"
        :login-protection-loading="loginProtectionLoading"
      />

      <!-- 登录记录 -->
      <LoginRecordsPanel 
        :security-settings="securitySettings"
        :login-logs="loginLogs"
        :login-logs-loading="loginLogsLoading"
        :login-logs-pagination="loginLogsPagination"
        @refresh="refreshLoginLogs"
        @page-change="handleLoginLogsPageChange"
      />
    </div>

    <!-- 修改密码对话框 -->
    <PasswordDialog 
      v-model="showPasswordDialog"
      @confirm="changePasswordAction"
    />

    <!-- 绑定邮箱对话框 -->
    <EmailBindDialog 
      v-model="showEmailBindDialog"
      @confirm="handleBindEmail"
    />
  </Layout>
</template>

<script setup name="SecuritySettingsView">
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import Cookies from 'js-cookie';
import { useUserStore } from '@/store/user';
import { changePassword } from '@/api/user';
import { 
  getSecuritySettings, 
  getSecurityScore, 
  bindEmail, 
  unbindEmail,
  enableLoginProtection,
  disableLoginProtection,
  getLoginLogs
} from '@/api/security';
import Layout from '@/components/layout/Layout.vue';
import SecurityOverview from '@/components/security/SecurityOverview.vue';
import SecuritySettingsPanel from '@/components/security/SecuritySettingsPanel.vue';
import LoginRecordsPanel from '@/components/security/LoginRecordsPanel.vue';
import PasswordDialog from '@/components/security/PasswordDialog.vue';
import EmailBindDialog from '@/components/security/EmailBindDialog.vue';

// 状态管理
const userStore = useUserStore();

// 安全设置和评分
const securitySettings = reactive({});
const securityScore = reactive({});

// 对话框显示状态
const showPasswordDialog = ref(false);
const showEmailBindDialog = ref(false);

// 登录保护相关
const loginProtectionLoading = ref(false);

// 登录日志相关
const loginLogs = ref([]);
const loginLogsLoading = ref(false);
const loginLogsPagination = reactive({
  page: 1,
  pageSize: 10,
  total: 0
});

// 计算安全评分
const calculateSecurityScore = () => {
  return securityScore.totalScore || 60;
};

// 获取进度条颜色
const getProgressColor = () => {
  const score = calculateSecurityScore();
  if (score < 70) return '#F56C6C';
  if (score < 85) return '#E6A23C';
  return '#67C23A';
};

// 格式化评分显示
const formatScore = () => {
  return `${calculateSecurityScore()}分`;
};

// 获取安全设置
const fetchSecuritySettings = async () => {
  try {
    const response = await getSecuritySettings();
    if (response.code === 0) {
      Object.assign(securitySettings, response.data);
    }
  } catch (error) {
    console.error('获取安全设置失败:', error);
  }
};

// 获取安全评分
const fetchSecurityScore = async () => {
  try {
    const response = await getSecurityScore();
    if (response.code === 0) {
      Object.assign(securityScore, response.data);
    }
  } catch (error) {
    console.error('获取安全评分失败:', error);
  }
};

// 获取登录日志
const fetchLoginLogs = async () => {
  try {
    loginLogsLoading.value = true;
    const response = await getLoginLogs(loginLogsPagination.page, loginLogsPagination.pageSize);
    if (response.code === 0) {
      loginLogs.value = response.data.list || [];
      loginLogsPagination.total = response.data.total || 0;
      loginLogsPagination.totalPages = response.data.totalPages || 0;
    }
  } catch (error) {
    console.error('获取登录日志失败:', error);
    ElMessage.error('获取登录日志失败，请重试');
  } finally {
    loginLogsLoading.value = false;
  }
};

// 刷新登录日志
const refreshLoginLogs = () => {
  fetchLoginLogs();
};

// 分页切换
const handleLoginLogsPageChange = (page) => {
  loginLogsPagination.page = page;
  fetchLoginLogs();
};

// 修改密码
const changePasswordAction = async (passwordData) => {
  try {
    const response = await changePassword(
      passwordData.oldPassword,
      passwordData.newPassword,
      passwordData.confirmPassword
    );
    
    if (response.code === 0) {
      ElMessage.success('密码修改成功，请重新登录');
      showPasswordDialog.value = false;
      
      // 清除cookie和状态，跳转到登录页
      Cookies.remove('virtual_bank_token');
      Cookies.remove('token');
      userStore.resetState();
      
      // 延迟跳转
      setTimeout(() => {
        window.location.href = '/login';
      }, 1500);
    }
  } catch (error) {
    console.error('修改密码失败:', error);
    ElMessage.error('修改密码失败，请重试');
  }
};

// 绑定邮箱
const handleBindEmail = async (emailData) => {
  try {
    const response = await bindEmail(emailData.email, emailData.verificationCode);
    
    if (response.code === 0) {
      ElMessage.success('邮箱绑定成功');
      showEmailBindDialog.value = false;
      
      // 重新获取数据
      await fetchSecuritySettings();
      await fetchSecurityScore();
    }
  } catch (error) {
    console.error('绑定邮箱失败:', error);
    ElMessage.error('绑定邮箱失败，请检查验证码是否正确');
  }
};

// 解绑邮箱
const handleUnbindEmail = () => {
  ElMessageBox.confirm('解绑邮箱后将失去邮箱安全验证功能，是否继续？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    try {
      const response = await unbindEmail('123456');
      
      if (response.code === 0) {
        ElMessage.success('邮箱解绑成功');
        
        // 重新获取数据
        await fetchSecuritySettings();
        await fetchSecurityScore();
      }
    } catch (error) {
      console.error('解绑邮箱失败:', error);
      ElMessage.error('解绑邮箱失败，请重试');
    }
  });
};

// 切换登录保护
const handleToggleLoginProtection = async (value) => {
  loginProtectionLoading.value = true;
  
  try {
    const response = value 
      ? await enableLoginProtection()
      : await disableLoginProtection('123456');
    
    if (response.code === 0) {
      ElMessage.success(`登录保护已${value ? '启用' : '禁用'}`);
      // 重新获取安全设置
      await fetchSecuritySettings();
    } else {
      // 如果失败，恢复原状态
      securitySettings.loginProtection = !value;
    }
  } catch (error) {
    console.error('切换登录保护失败:', error);
    ElMessage.error('操作失败，请重试');
    // 恢复原状态
    securitySettings.loginProtection = !value;
  } finally {
    loginProtectionLoading.value = false;
  }
};

// 页面初始化
onMounted(async () => {
  await fetchSecuritySettings();
  await fetchSecurityScore();
  await fetchLoginLogs();
});
</script>

<style scoped>
.security-page {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #303133;
  font-size: 24px;
  font-weight: 600;
}

.page-header p {
  margin: 8px 0 0 0;
  color: #909399;
  font-size: 14px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .security-page {
    padding: 10px;
  }
}
</style>
